import React, { Component } from "react";
import { SafeAreaView, Text, View, StyleSheet, Image, TextInput, TouchableOpacity, FlatList, ActivityIndicator, DeviceEventEmitter } from 'react-native';

import Constant from '../../utils/Constant'//全局变量
import { getImgUrl, formatTimestamp, getMsgContentShow } from '../../utils/ComFunction';
import HttpUtils from "../../utils/HttpUtils";
import HttpUrls from "../../utils/HttpUrls";
import Header from "../../components/header";
import Loading from "../../utils/Loading";
import OpenIMSDKRN, { OpenIMEmitter, MessageItem } from 'open-im-sdk-rn';
import AsyncImage from '../../components/image/AsyncImage';
import LinearGradient from 'react-native-linear-gradient';

let navigation

export default class MessageCenterPage extends Component {

    constructor(props) {
        super(props);
        this.state = {
            msgList: [],
            pageNo: 1,

            isRefresh: false,
            showFoot: 0,
            keyWord: '',
            isFranchisee: 0,
            targetIndex: 0,
            noticeMsgUnreadCount: 0,
            waitMsgUnreadCount: 0
        };
        this.flatListRef = React.createRef();
    }

    componentDidMount() {
        this.openImLogin()
        OpenIMEmitter.addListener('onRecvNewMessages', (data) => {
            console.log('onRecvNewMessages', data);
            DeviceEventEmitter.emit('updateUnreadMsg', data);
            setTimeout(() => {
                if (data) {
                    this.setState({
                        pageNo: 1,
                        msgList: [],
                        isRefresh: true
                    }, function () {
                        this.getMsgList()
                    })

                }
            }, 1000)


        });
        this.scrollToUnreadMsg = DeviceEventEmitter.addListener('scrollToUnreadMsg', (data) => {
            this.scrollToUnreadMsgByIndex()
        })

        this.setState({
            isFranchisee: Constant.userInfo.isFranchisee
        })
        if (this.Loading) {
            this.Loading.show()
        }
        this.getMsgList()

        this.backHome = DeviceEventEmitter.addListener('backHome', (result) => {
            if (result && result.index == 3) {
                navigation.navigate('WorkCenterPage')
            }
        })

        this._unsubscribe = this.props.navigation.addListener('focus', () => {
            DeviceEventEmitter.emit('homeListener', {isInHome:false,index:3});
            this.messageGetBrief()
        });
    }

    componentWillUnmount() {
        OpenIMEmitter.removeAllListeners('onRecvNewMessages');
        if (this.scrollToUnreadMsg) {
            this.scrollToUnreadMsg.remove()
        }
        this._unsubscribe();
        if(this.backHome){
            this.backHome.remove();
        }
    }

    scrollToUnreadMsgByIndex() {
        if (this.state.msgList.length == 0) {
            return
        }

        let targetIndex = this.state.targetIndex


        for (let index = 0; index < this.state.msgList.length; index++) {
            if (this.state.msgList[index].imConversationInfo.unreadCount > 0 && index > targetIndex) {
                targetIndex = index
                break;
            }
        }

        this.setState({
            targetIndex: targetIndex
        })
        this.scrollToIndex(targetIndex)

    }

    openImLogin() {
        OpenIMSDKRN.getLoginStatus(Constant.userInfo.username).then((result) => {
            console.log('getLoginStatus', result);
            if (result == 1) {
                OpenIMSDKRN.login({
                    userID: Constant.userInfo.imUserId,
                    token: Constant.userInfo.imToken,
                }, this.state.operationID)
                    .then((result) => {
                        console.log('login-success', result);
                    }).catch(err => {
                        console.log('login-error=', err);
                    });
            } else if (result == 3) {

            }
        })
    }

    render() {
        navigation = this.props.navigation;
        return (
            <View style={styles.container}>
                <Header navigation={navigation} isAtRoot={true} Title={'消息'} hideSepLine={true} bgColor={'#f9f9f9'}></Header>

                <View style={styles.searchContain}>
                    <Image style={styles.searchIcon} source={require('source/image/comm/icon_sc_search.png')}></Image>
                    <TextInput
                        style={styles.searchInput}
                        placeholder={'搜索联系人'}
                        onChangeText={(text) => { this.setState({ keyWord: text }) }}>

                    </TextInput>

                    <TouchableOpacity
                        onPress={() => {
                            this.setState({
                                pageNo: 1,
                                msgList: []
                            }, function () {
                                this.getMsgList()
                            })
                        }}>
                        <Text style={styles.searchText}>| 搜索</Text>
                    </TouchableOpacity>

                </View>

                <TouchableOpacity
                    style={[styles.msgItemContain, { marginTop: 10 }]}
                    onPress={() => { this.props.navigation.navigate('NoticeMsgListPage', { title: '通知消息' }) }}>
                    <View style={{ width: 52 }}>
                        <Image style={styles.itemMsgIcon} source={require('source/image/msg/msg_notice.png')}></Image>
                        {this.state.noticeMsgUnreadCount <= 0 ? null :
                            <View style={styles.msgCountContain}>
                                <Text style={styles.msgCountText}>{this.state.noticeMsgUnreadCount}</Text>
                            </View>
                        }


                    </View>
                    <View style={styles.contentContain}>
                        <Text style={styles.msgItemTitleText}>通知消息</Text>
                        {/* <Text style={styles.contentText}></Text>
                        <Text style={styles.timeText}></Text> */}
                    </View>
                </TouchableOpacity>

                <TouchableOpacity
                    style={[styles.msgItemContain, { marginTop: 0 }]}
                    onPress={() => { this.props.navigation.navigate('NoticeMsgListPage', { msgType: 5, title: '待办事件' }) }}>
                    <View style={{ width: 52 }}>
                        <Image style={styles.itemMsgIcon} source={require('source/image/msg/msg_todo.png')}></Image>
                        {this.state.waitMsgUnreadCount <= 0 ? null :
                            <View style={styles.msgCountContain}>
                                <Text style={styles.msgCountText}>{this.state.waitMsgUnreadCount}</Text>
                            </View>
                        }


                    </View>
                    <View style={styles.contentContain}>
                        <Text style={styles.msgItemTitleText}>待办事件</Text>
                        {/* <Text style={styles.contentText}></Text>
                        <Text style={styles.timeText}></Text> */}
                    </View>
                </TouchableOpacity>

                <FlatList
                    ref={this.flatListRef}
                    data={this.state.msgList}
                    renderItem={this.renderMsgItem.bind(this)}
                    keyExtractor={(item, index) => index + ''}
                    style={{ flex: 1, backgroundColor: '#fff', width: '100%' }}
                    extraData={this.state}
                    ListFooterComponent={this._renderFooter.bind(this)}
                    onEndReached={this._onEndReached.bind(this)}
                    onEndReachedThreshold={0.2}
                    onRefresh={this.refreshData}
                    refreshing={this.state.isRefresh}

                >

                </FlatList>

                <Loading onRef={(ref) => (this.Loading = ref)}></Loading>

            </View>
        );
    }

    // 滚动到指定索引位置
    scrollToIndex = (targetIndex) => {
        const index = parseInt(targetIndex);

        if (isNaN(index) || index < 0 || index >= this.state.msgList.length) {

            return;
        }

        this.flatListRef.current.scrollToIndex({
            index,
            animated: true,
            viewPosition: 0, // 0表示顶部，0.5表示中间，1表示底部
        });
    };

    refreshData = () => {
        this.setState({
            pageNo: 1,
            msgList: [],
            isRefresh: true
        }, function () {
            this.getMsgList()
        })
    }

    renderMsgItem({ item, index }) {
        return (
            <TouchableOpacity
                key={index}
                style={styles.msgItemContain2}
                activeOpacity={0.8}
                onPress={() => {
                    this.clearUnreadCount(index)
                    let msgParams = {
                        imGroupId: item.imGroupId + '',
                        carId: item.consultingCarId + '',
                        quotationRecordId: item.quotationRecord && item.quotationRecord.quotationRecordId ? item.quotationRecord.quotationRecordId : '',
                    }

                    this.props.navigation.navigate('MessageChat', msgParams);

                   
                    
                }}>

                <View style={{ width: 52 }}>
                    <AsyncImage style={styles.itemMsgIcon} source={{ uri: this.getConversationImg(item) }}></AsyncImage>
                    {item.imConversationInfo.unreadCount <= 0 || item.imConversationInfo.msgInfo.contentType == 1501 ?
                        null :
                        <View style={styles.msgCountContain}>
                            <Text style={styles.msgCountText}>{item.imConversationInfo.unreadCount}</Text>
                        </View>
                    }


                </View>

                <View style={styles.contentContain}>
                    <Text style={styles.msgItemTitleText}>{this.getMsgTitle(item)}</Text>
                    <Text style={styles.contentText} numberOfLines={1} ellipsizeMode={'tail'}>{getMsgContentShow(item.imConversationInfo.msgInfo)}</Text>
                    <Text style={styles.timeText}>{formatTimestamp(item.imConversationInfo.msgInfo.LatestMsgRecvTime)}</Text>
                </View>
                {
                    item.carMainPic ?
                        <View>
                            <AsyncImage style={styles.carImg} source={{ uri: getImgUrl(item.carMainPic) }}></AsyncImage>
                            {Constant.userInfo.roleName == '老板' && Constant.userInfo.isFranchisee == '1' ?
                                <View style={{ position: 'absolute', right: 0, bottom: 0, left: 0 }}>
                                    <LinearGradient start={{ x: 0, y: 0 }} end={{ x: 0, y: 1 }}
                                        colors={['rgba(0,0,0,0.02)', 'rgba(0,0,0,0.28)']}
                                        style={{ justifyContent: 'center', alignItems: 'center', height: 20, borderBottomLeftRadius: 4, borderBottomRightRadius: 4 }}>
                                        <Text style={{ fontSize: 10, color: '#FFE000' }}>{item.sellerUserName}</Text>

                                    </LinearGradient>

                                </View>
                                : null
                            }

                        </View>

                        :
                        null
                }

            </TouchableOpacity>
        )

    }

    clearUnreadCount(index) {

        let temp = []
        this.state.msgList.map((item, i) => {
            if (i == index) {
                item.imConversationInfo.unreadCount = 0
            }
            temp.push(item)
        })
        this.setState(
            {
                msgList: temp
            }
        )
    }

    getConversationImg(item) {
        if (Constant.userInfo.merchantId == item.buyerMerchantId) {//自己是买家，显示对方头像
            return getImgUrl(item.sellerUserLogo)
        } else {
            return getImgUrl(item.buyerUserLogo)
        }
    }

    getMsgTitle(item) {
        if (item.conversationType == 1) {//报价会话
            if (this.state.isFranchisee == 1) {
                return item.buyerUserName + '@' + item.buyerMerchantName
            } else {
                return item.sellerUserName + '@' + item.sellerMerchantName
            }
        } else {
            if (Constant.userInfo.merchantId == item.buyerMerchantId) {//自己是买家，显示卖家信息
                return item.sellerUserName + '@' + item.sellerMerchantName
            } else {
                return item.buyerUserName + '@' + item.buyerMerchantName
            }
        }

    }



    getCommonSubText(itemInfo) {

        let title = ''
        if (itemInfo.userTitle && itemInfo.userTitle.length > 0) {
            itemInfo.userTitle.map((item, index) => {
                if (item.merchantId == Constant.userInfo.merchantId) {
                    title = item.title
                }
            })
            if (title == '') {
                title = itemInfo.title
            }
        } else {
            title = itemInfo.title
        }
        return title
    }

    _onEndReached() {
        console.log('_onEndReached', this.state.showFoot)
        if (this.state.showFoot != 0) {
            return null;
        }

        let nextPage = this.state.pageNo + 1

        this.setState({ showFoot: 2, pageNo: nextPage },
            function () {
                this.getMsgList();
            });


    }

    _renderFooter() {
        if (this.state.msgList.length == 0) {
            return null;
        }
        if (this.state.showFoot === 1) {
            return null;
        } else if (this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator size="small" color="#999" />
                    <Text style={styles.loadMoreTextStyle}>正在加载更多数据...</Text>
                </View>
            );
        } else if (this.state.showFoot === 0) {
            return null;
        }
    }

    getMsgList() {

        let params = {
            pageNo: this.state.pageNo,
            pageSize: 20,
            imUserId: Constant.userInfo.imUserId,
            role: Constant.userInfo.isFranchisee == 1 ? '2' : '1',
            source: 2
        }

        if (this.state.keyWord != '') {
            params.keyWord = this.state.keyWord

        }

        HttpUtils.postRequest(HttpUrls.getUserConversation, params)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide()
                }

                let code = result.code
                if (code == 0) {

                    let resultList = result.data.resultList
                    console.log(resultList)
                    if (resultList.length > 0) {


                        if (resultList.length < 20) {

                            this.setState({
                                showFoot: 1
                            })
                        } else {
                            this.setState({
                                showFoot: 0
                            })
                        }

                        this.setState({
                            msgList: this.state.msgList.concat(resultList),
                        })

                    } else {

                        this.setState({
                            showFoot: 1
                        })
                    }

                    this.setState({
                        isRefresh: false,

                    })
                } else {
                    this.setState({
                        isRefresh: false,

                    })
                }
            })
            .catch((error) => {
                if (this.Loading) {
                    this.Loading.hide()
                }
                this.setState({
                    isRefresh: false,

                })
            });
    }


    messageGetBrief() {

        let params = {

        }

        HttpUtils.postRequest(HttpUrls.messageGetBrief, params)
            .then((result) => {
                let code = result.code
                if (code == 0) {
                    let data = result.data
                    // {"carInfoMsgCount": 0, "carSubCount": 0, "contractOrderCount": 0, "sysMsgCount": 0, "unionMsgCount": 0}
                    this.setState({
                        noticeMsgUnreadCount: data.sysMsgCount + data.carInfoMsgCount,
                        waitMsgUnreadCount: data.contractOrderCount
                    })
                }
            })
            .catch((error) => {

            });
    }

};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f9f9f9',
    },

    searchContain: {
        flexDirection: 'row',
        alignItems: 'center',
        marginLeft: 15,
        marginRight: 15,
        backgroundColor: '#fff',
        height: 40,
        borderRadius: 6,
        paddingLeft: 10,
        paddingRight: 10
    },

    searchIcon: {

        width: 20,
        height: 20,
    },

    searchText: {

        marginLeft: 5,
        fontSize: 14,
        color: '#333'
    },
    searchInput: {
        flex: 1,
        marginLeft: 10,
        fontSize: 14,
        color: '#333'
    },

    itemMsgIcon: {
        width: 48,
        height: 48,
        borderRadius: 48,
        backgroundColor: '#f6f6f6'
    },

    msgItemContain: {
        flexDirection: 'row',
        alignItems: 'center',
        marginLeft: 15,
        marginRight: 15,
        paddingTop: 12,
        paddingBottom: 12,
        borderBottomWidth: 0.5,
        borderBottomColor: '#e4e4e4'

    },

    msgCountContain: {
        backgroundColor: '#ED542E',
        height: 14,
        borderRadius: 14,
        minWidth: 14,
        alignItems: 'center',
        justifyContent: 'center',
        position: 'absolute',
        top: 0,
        right: 0
    },
    msgCountText: {
        fontSize: 8,
        color: '#fff'
    },
    contentContain: {
        flexDirection: 'column',
        marginLeft: 10,
        flex: 1
    },
    msgItemTitleText: {
        fontSize: 16,
        color: '#333',
        fontWeight: 'bold'
    },
    contentText: {
        marginTop: 5,
        fontSize: 13,
        color: '#999999'
    },
    timeText: {
        marginTop: 3,
        fontSize: 10,
        color: '#999999'
    },

    msgItemContain2: {
        flexDirection: 'row',
        alignItems: 'center',
        marginLeft: 15,
        marginRight: 15,
        paddingTop: 12,
        paddingBottom: 12,
        borderBottomWidth: 0.5,
        borderBottomColor: '#e4e4e4'

    },

    carImg: {
        width: 62,
        height: 62,
        backgroundColor: '#f6f6f6',
        borderRadius: 4
    },
    footer: {
        flexDirection: 'row',
        height: 40,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#f6f6f6'
    },
    loadMoreTextStyle: {
        fontSize: 14,
        color: '#999999',
        marginStart: 10,
    },

});